const { app, BrowserWindow, ipcMain, Menu } = require("electron");
const path = require("path");
const os = require("os");

const InitWindowAttr = {
  width: 800,
  height: 600,
  webPreferences: {
    preload: path.join(__dirname, "/preload/index.js"),
  },
};
ipcMain.on("send", (event, title) => {
  const webContents = event.sender;
  const win = BrowserWindow.fromWebContents(webContents);
  win.setTitle(title);
});

const getSystemInfo = () => {
  return {
    totalMem: os.totalmem(),
    freeMem: os.freemem(),
    platform: os.platform(),
  };
};
const createWindow = () => {
  const win = new BrowserWindow(InitWindowAttr);

  //设置自定义菜单
  const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          click: () => win.webContents.send("update-counter", getSystemInfo()),
          label: "Increment",
        },
        {
          click: () => win.webContents.send("update-counter", -1),
          label: "Decrement",
        },
      ],
    },
  ]);
  setInterval(() => {
    win.webContents.send("update-counter", getSystemInfo());
  }, 1000);
  Menu.setApplicationMenu(menu);
  win.loadFile("./src/index.html");
  win.webContents.openDevTools();
};

app.whenReady().then(() => {
  console.log("--------- start ----------");
  createWindow();
});
